package cn.com.paycn.ken.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.paycn.ken.hbm.LoginUser;
import cn.com.paycn.ken.hbm.Member;
import cn.com.paycn.ken.service.LoginUserService;
import cn.com.paycn.ken.service.LogoService;
import cn.com.paycn.ken.utils.AuthImageUtils;
import cn.com.paycn.ken.utils.exception.LoginException;

@Controller
@RequestMapping({ "/auth" })
public class AuthController {
	@Autowired
	private LoginUserService loginUserService;
	@Autowired
	private LogoService logoService;
	
	@Autowired
	private AuthenticationManager myAuthenticationManager;

	@RequestMapping
	public ModelAndView index() {
		ModelAndView view = new ModelAndView("login");
		view.addObject("logoPath", this.logoService.getLogo());
		return view;
	}

	@RequestMapping(value = { "/login" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public String login(LoginUser user, HttpServletRequest request,
			HttpSession session, RedirectAttributes redirectAttrs) {
		redirectAttrs.addFlashAttribute("username", user.getUsername());

		if (session.getAttribute("authCode") == null) {
			redirectAttrs.addFlashAttribute("messageError", "验证码失效");
		} else if ((StringUtils.isBlank(user.getUsername()))
				|| (StringUtils.isBlank(user.getPassword())))
			redirectAttrs.addFlashAttribute("messageError", "请输入用户名和密码");
		else if (!user.getAuthCode().equalsIgnoreCase(
				String.valueOf(session.getAttribute("authCode"))))
			redirectAttrs.addFlashAttribute("messageError", "验证码验证失败");
		else {
			try {
				Member member = this.loginUserService.login(user, request);
				session.setAttribute("session_info", member);
				return "redirect:/home.html";
			} catch (LoginException e) {
				redirectAttrs.addFlashAttribute("messageError", e.getMessage());
			}
		}

		return "redirect:/auth.html";
	}

	@RequestMapping({ "/code" })
	public void getCode(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		AuthImageUtils i = AuthImageUtils.newInstance(this.width, this.height);
		i.setBrightness((short) 2);

		resp.setHeader("Pragma", "no-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0L);
		resp.setContentType("image/jpeg");
		i.output(resp.getOutputStream());

		HttpSession session = req.getSession();
		session.setAttribute("authCode", i.getAuthCode());
	}

	private int width = 84;
	private int height = 34;

}
